﻿using FI.BatchJob.Web.Data;
using FI.BatchJob.Web.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace src.Areas.User.Controllers
{

    [Authorize(Roles = "Admin")]
    public class UserController : Controller
    {
        private readonly ILogger _logger;
        private readonly ApplicationDbContext _context;
        private readonly UserManager<IdentityUser> _userManager;

        public UserController(ApplicationDbContext context, ILogger<UserController> logger,
              UserManager<IdentityUser> userManager)
        {
            _context = context;
            _logger = logger;
            _userManager = userManager;
        }

        public IActionResult Index()
        {
            return View(_userManager.Users.ToList());

        }

        [Authorize(Roles = "Admin")]
        [HttpGet]
        public IActionResult Add()
        {
            return View();
        }
        [HttpPost]
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> Add([FromBody]UserRegModel data)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            try
            {

                var user = new IdentityUser
                {
                    UserName = data.Email,
                    Email = data.Email
                };

                var result = await _userManager.CreateAsync(user, data.Password);

                if (result.Succeeded)
                {
                    var rresult = await _userManager.AddToRoleAsync(user, "Customer");

                    if (rresult.Succeeded)
                    {
                        _logger.LogInformation("User created a new account with password.");

                        return Json(new { success = true, message = "用户建立成功." });
                    }
                    else
                    {
                        _logger.LogInformation("User role created unsucceedfully.");

                        var error = rresult.Errors.FirstOrDefault();
                        if (error != null) _logger.LogError(rresult.Errors.FirstOrDefault().Description);
                        return Json(new { success = false, message = "用户角色建立失败" });
                    }

                }
                else
                {
                    _logger.LogInformation("User created unsucceedfully.");

                    var error = result.Errors.FirstOrDefault();
                    if (error != null) _logger.LogError(result.Errors.FirstOrDefault().Description);

                    return Json(new { success = false, message = "用户建立失败" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }
        [HttpGet]

        public IActionResult ChangePassword(string id)
        {
            return View(new UserChangePasswordModel
            {
                Id = id,
            });
        }
        [HttpPost]
        public async Task<IActionResult> Remove(string id)
        {
            var user = await _userManager.FindByIdAsync(id);

            if (user != null) await _userManager.DeleteAsync(user);

            return Json(new { success = true, message = "用户删除成功." });

        }
        [HttpPost]
        public async Task<IActionResult> ChangePassword([FromBody]UserChangePasswordModel data)
        {
            var user = await _userManager.FindByIdAsync(data.Id);
            if (user == null)
            {
                // Don't reveal that the user does not exist
                return Json(new { success = false, message = "用户不存在" });
            }
            var code = await _userManager.GeneratePasswordResetTokenAsync(user);
            var result = await _userManager.ResetPasswordAsync(user, code, data.Password);
            if (result.Succeeded)
            {
                return Json(new { success = true, message = "修改密码成功" });
            }
            else
            {
                return Json(new { success = false, message = "修改密码失败" });
            }
        }





    }
}
